import React, {FC, useState, useEffect, useRef} from 'react';
import "./Login.scss";
import {Form, Input, Button, message} from 'antd';
import {Link, useNavigate} from "react-router-dom";
// 导入正则规则
import {reg} from "../../utils";
import api from "../../api";

const Register: FC = () => {
    const [form] = Form.useForm();
    // const [, forceUpdate] = useState({});
    // 发送验证码按钮状态
    const [sendCodeState, setSendCodeState] = useState(false);
    // 发送验证码按钮文本
    const [sendCodeText, setsendCodeText] = useState("获取验证码");
    const navigate = useNavigate();

    useEffect(() => {
        // forceUpdate({});
    }, []);
    const onCode = async () => {
        // 触发手机号字段验证
        try {
            await form.validateFields(["phone"])
        } catch (e) {
            return;
        }
        // 获取手机号
        let phone = form.getFieldValue("phone");
        // 发送验证码
        api.sendCode({phone}).then(res => {
            if (res.code === 200) {
                message.success("验证码发送成功");
            } else {
                message.error(res.msg);
            }
        }).catch((err) => {
            message.error(err.message);
        })
        // 防狂点
        setSendCodeState(true);
        let time = 60
        // 定时器
        let timer: NodeJS.Timeout | undefined;
        // 延时器
        let delayer: NodeJS.Timeout | undefined
        clearInterval(timer as NodeJS.Timeout)
        clearTimeout(delayer as NodeJS.Timeout)
        setsendCodeText(`${time}s`)
        timer = setInterval(() => {
            time--
            setsendCodeText(`${time}s`)
        }, 1000)
        delayer = setTimeout(() => {
            setSendCodeState(false)
            setsendCodeText("获取验证码")
            clearInterval(timer as NodeJS.Timeout)
            clearTimeout(delayer as NodeJS.Timeout)
        }, 60000)
    }

    return (
        <div className="content">
            <video src={require("../../assets/background.mp4")} autoPlay loop muted></video>
            <div className="box">
                <h1 style={{textAlign: "center"}}>注册</h1>
                <Form form={form} name="horizontal_login" layout="vertical" onFinish={(values) => {
                    delete values.confirmPassword;
                    // console.log(values);
                    // 注册
                    api.register(values).then(res => {
                        if (res.code === 200) {
                            message.success("注册成功");
                            // 跳转到登录页
                            navigate("/login?phone=" + values.phone);
                        } else {
                            message.error(res.msg);
                        }
                    }).catch(err => {
                        message.error(err.message);
                    })
                }}>
                    <Form.Item label="用户名" name="username"
                               rules={[{required: true, message: '用户名是必填项'},]}>
                        <Input placeholder="请输入用户名"/>
                    </Form.Item>
                    <Form.Item label="手机号" name="phone"
                               rules={[
                                   {required: true, message: '手机号是必填项'},
                                   {pattern: reg.phone, message: '请输入正确的手机号'}
                               ]}>
                        <Input type="tel" placeholder="请输入手机号"/>
                    </Form.Item>
                    {/* 验证码 */}
                    <div style={{display: 'flex', alignItems: "flex-end", justifyContent: "space-between"}}>
                        <Form.Item style={{width: "70%"}} label="验证码" name="code" rules={[
                            {required: true, message: '验证码是必填项'},
                            {pattern: reg.code, message: '请输入正确的四位数组验证码'}
                        ]}>
                            <Input placeholder="请输入验证码"/>
                        </Form.Item>
                        <Form.Item style={{width: "25%"}}>
                            <Button style={{width: "100%"}} type="primary" disabled={sendCodeState}
                                    onClick={onCode}>{sendCodeText}</Button>
                        </Form.Item>
                    </div>
                    <Form.Item dependencies={['confirmPassword']} label="密码" name="password"
                               rules={[
                                   {required: true, message: '密码是必填项'},
                                   {
                                       pattern: reg.password,
                                       message: '请输入6-16的密码包含数字、字母、字符中的两种'
                                   },
                                   ({getFieldValue}) => ({
                                       validator(_, value) {
                                           if (!value || getFieldValue('confirmPassword') === value) {
                                               return Promise.resolve();
                                           }
                                           return Promise.reject(new Error('两次输入的密码不一致'));
                                       },
                                   }),
                               ]}>
                        <Input.Password type="password" placeholder="请输入密码"/>
                    </Form.Item>
                    <Form.Item dependencies={['password']} label="确认密码" name="confirmPassword"
                               rules={[
                                   {required: true, message: '确认密码是必填项'},
                                   {pattern: reg.password, message: '请输入6-16的密码包含数字、字母、字符中的两种'},
                                   ({getFieldValue}) => ({
                                       validator(_, value) {
                                           if (!value || getFieldValue('password') === value) {
                                               return Promise.resolve();
                                           }
                                           return Promise.reject(new Error('两次输入的密码不一致'));
                                       },
                                   }),
                               ]}>
                        <Input.Password type="password" placeholder="请确认密码"/>
                    </Form.Item>
                    <Form.Item>
                        <div style={{display: "flex", justifyContent: "space-between"}}>
                            <Link to="/login">有账号，去登录</Link>
                            <Link to="/forget">忘记密码，去重置</Link>
                        </div>
                    </Form.Item>
                    <Form.Item>
                        <Button block type="primary" htmlType="submit">注册</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button block htmlType="reset">重置</Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
export default Register;